package com.xindaoapp.happypet.view;


import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap.Config;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.util.LogUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.utils.CommonParameter;

/**
 * 禁止滚动的viewPager，商城banner用
 * 
 * @author Yangqing
 * 
 */
public class RollViewPager2 extends ViewPager {
    boolean isCanScroll;// 是否可以滑动到下一页，默认false

    public RollViewPager2(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    private Context ct;
    private List<View> dotList;
    private int dotFocus;
    private int dotNormal;
    private TextView tvDescription;
    private float mLastMotionX;
    private float mLastMotionY;

    public interface OnPagerClickCallBack {
        public void pagerClickCallBack(int position);
    }

    public interface MyOnTouchCllickCallBack {
        public void OnTouchCllick(int position);
    }

    public MyOnTouchCllickCallBack onTouchCllickCallBack;

    public RollViewPager2(Context ct, List<View> dotList, int dotFocus, int dotNormal,
            MyOnTouchCllickCallBack myOnTouchCllickCallBack) {
        super(ct);
        this.ct = ct;
        this.dotList = dotList;
        this.dotFocus = dotFocus;
        this.dotNormal = dotNormal;
        bitmapUtils = new BitmapUtils(ct);
        bitmapUtils.configDefaultBitmapConfig(Config.ARGB_4444);
        taskPager = new TaskPager();
        this.onTouchCllickCallBack = myOnTouchCllickCallBack;
        myOnTouchListener = new MyOnTouchListener();
    }

    public class MyOnTouchListener implements OnTouchListener {

        private long satartCurrentTimeMillis;

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            float currentX = arg1.getX();
            float currentY = arg1.getY();
            switch (arg1.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    satartCurrentTimeMillis = System.currentTimeMillis();
                    handler.removeCallbacksAndMessages(null);
                    break;

                case MotionEvent.ACTION_UP:
                    long duration = System.currentTimeMillis() - satartCurrentTimeMillis;
                    float upX = arg1.getX();
                    if (duration < 500 && upX == currentX) {
                        onTouchCllickCallBack.OnTouchCllick(currentItem);
                    }
                    startRoll();
                case MotionEvent.ACTION_CANCEL:
                    startRoll();
                    break;
                case MotionEvent.ACTION_MOVE:
                    handler.removeCallbacksAndMessages(null);
                    break;
            }
            return true;
        }

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        final float x = ev.getX();
        final float y = ev.getY();
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // getParent().requestDisallowInterceptTouchEvent(true);
                mLastMotionX = x;
                mLastMotionY = y;
                break;
            case MotionEvent.ACTION_MOVE:
                if (Math.abs(x - mLastMotionX) < Math.abs(y - mLastMotionY)) {
                    getParent().requestDisallowInterceptTouchEvent(false);
                    LogUtils.d("in listview");
                } else {
                    // getParent().requestDisallowInterceptTouchEvent(true);
                    LogUtils.d("in viewpager");
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                getParent().requestDisallowInterceptTouchEvent(false);
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    public class TaskPager implements Runnable {

        @Override
        public void run() {
            currentItem = (currentItem + 1) % imageUrlList.size();
            handler.obtainMessage().sendToTarget();
        }

    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            RollViewPager2.this.setCurrentItem(currentItem);
            startRoll();
        };
    };

    // 需要显示的文本内容
    private List<String> titleList;

    public void setTitle(TextView tvDescription, List<String> titleList) {
        this.tvDescription = tvDescription;
        this.titleList = titleList;
        if (tvDescription != null && titleList != null && titleList.size() > 0) {
            tvDescription.setText(titleList.get(0));
        }
    }

    private List<String> imageUrlList;
    private ViewPagerAdatper adapter;
    private BitmapUtils bitmapUtils;
    private TaskPager taskPager;

    public void setImageUrl(List<String> imageUrlList) {
        this.imageUrlList = imageUrlList;
    }

    public boolean hasSetAdapter = false;

    public void startRoll() {
        if (!hasSetAdapter) {
            hasSetAdapter = true;
            this.setOnPageChangeListener(new MyOnPageChangeListener());
            adapter = new ViewPagerAdatper();
            this.setAdapter(adapter);
        }
        // handler.postDelayed(taskPager, 4000);
    }

    public int currentItem = 0;
    private MyOnTouchListener myOnTouchListener;
    private SharedPreferences sp;

    public class MyOnPageChangeListener implements OnPageChangeListener {
        int oldPositionItem = 0;

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageSelected(int arg0) {
            currentItem = arg0 % titleList.size();
            if (tvDescription != null) {
                tvDescription.setText(titleList.get(arg0 % titleList.size()));
            }
            if (dotList != null && dotList.size() > 0) {
                dotList.get(arg0 % titleList.size()).setBackgroundResource(dotNormal);
                dotList.get(oldPositionItem % titleList.size()).setBackgroundResource(dotFocus);
            }
            oldPositionItem = arg0;
        }

    }

    public class ViewPagerAdatper extends PagerAdapter {

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // ImageView iv = (ImageView) View.inflate(ct, R.layout.point_imageview, null);
            // ((ViewPager) container).addView(view);
            // ImageView iv = (ImageView) view.findViewById(R.id.image);
            ImageView iv = new ImageView(ct);
            iv.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    CommonParameter.sScreenWidth * 248 / 640));
            // RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(10, 10);
            // iv.setLayoutParams(layoutParams);
            iv.setScaleType(ScaleType.FIT_XY);
            if (CommonParameter.isLoadImg) {
                ImageLoader.getInstance().displayImage(imageUrlList.get(position % dotList.size()),
                        iv);
            } else {
                iv.setImageResource(R.drawable.picture_loading);
            }
            // bitmapUtils.display(iv, imageUrlList.get(position));
            iv.setOnTouchListener(myOnTouchListener);
            container.addView(iv);
            return iv;
        }

        @Override
        public int getCount() {
            return 100000;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

    }

    @Override
    protected void onDetachedFromWindow() {
        handler.removeCallbacksAndMessages(null);
        super.onDetachedFromWindow();
    }


    @Override
    public void scrollTo(int x, int y) {
        if (isCanScroll) {
            super.scrollTo(x, y);
        }
    }

}
